package com.javaeedev.junit;

import java.io.IOException;
import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.RequestProcessor;

/**
 * This Struts extension point is used to inject object into Action when action 
 * is created. Using this RequestProcessor makes DI (dependency injection) 
 * possible in Struts.
 * 
 * @author Xuefeng
 */
public class InjectRequestProcessor extends RequestProcessor {

    private Service service = new ServiceStub();

    /**
     * Since we want to inject our Service into each Action instance, we need 
     * override this method to do injection.
     */
    protected Action processActionCreate(
            HttpServletRequest request,
            HttpServletResponse response,
            ActionMapping mapping) throws IOException
    {
        Action action = super.processActionCreate(request, response, mapping);
        // try to call setService(Service) method:
        try {
            Method m = action.getClass().getMethod("setService", new Class[] { Service.class });
            m.invoke(action, new Object[] { service });
        }
        catch(Exception e) {
            e.printStackTrace();
        }
        return action;
    }

}
